﻿using BW.EatRabbit.API.Application.Commands;
using BW.EatRabbit.API.Dtos;
using BW.EatRabbit.Domain;
using BW.EatRabbit.ErrorCode;
using BW.EatRabbit.Infrastructure.Interfaces;
using MediatR;

namespace BW.EatRabbit.API.Application.CommandHandlers
{
    public class BasicInformationQueryCommandHandler : IRequestHandler<BasicInformationQueryCommand, APIResult<APIPaging<BasicDTO>>>
    {
        private readonly IBaseRepository<BasicInformation> basicinformationRepository;
        private readonly IBaseRepository<Goods> goodsRepository;
        public BasicInformationQueryCommandHandler(IBaseRepository<BasicInformation> basicinformationRepository, IBaseRepository<Goods> goodsRepository)
        {
            this.basicinformationRepository = basicinformationRepository;
            this.goodsRepository = goodsRepository;

        }
        public Task<APIResult<APIPaging<BasicDTO>>> Handle(BasicInformationQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<BasicDTO>> result = new APIResult<APIPaging<BasicDTO>>();
            result.Code = ResultCode.查询成功;
            result.Message = ResultCode.查询成功.ToString();

            var list = from a in basicinformationRepository.GetAll()
                       join b in goodsRepository.GetAll() on a.GoodsId equals b.GoodsId
                       where !a.IsDeleted
                       select new BasicDTO
                       {
                           BasicInforId=a.BasicInforId,
                           GoodsId=b.GoodsId,
                           GoodsName=b.GoodsName,
                           ProductionBatch=a.ProductionBatch,
                           ShelfLife=a.ShelfLife,
                           License=a.License,
                           Completeness=a.Completeness,
                           Producer=a.Producer,
                           CoverImage=a.CoverImage,
                           CreatedTime=a.CreatedTime,
                           Creator=a.Creator,
                           UpdatedTime=a.UpdatedTime,
                           Updator=a.Updator
                       };

            int recordcount = list.Count();
            int pagecount = (int)Math.Ceiling(recordcount * 1.0 / request.PageSize);

            list = list.OrderByDescending(x => x.BasicInforId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            APIPaging<BasicDTO> paing = new APIPaging<BasicDTO>();
            paing.RecordCount = recordcount;
            paing.PageCount = pagecount;
            paing.List = list.ToList();

            result.Data = paing;

            return Task.FromResult(result);
        }
    }
}
